 /*
  * Copyright (c) 2021, 2023, yishun.cn All rights reserved.
  *
  */
 package cn.shun.controller;

 import cn.hutool.core.codec.Base64;
 import cn.hutool.core.io.FileUtil;
 import cn.hutool.core.util.IdUtil;
 import cn.hutool.core.util.StrUtil;
 import cn.hutool.poi.excel.ExcelReader;
 import cn.hutool.poi.excel.ExcelUtil;
 import cn.shun.dao.MemberDao;
 import cn.shun.dao.MyFileDao;
 import cn.shun.model.UploadInfo;
 import cn.shun.model.Member;
 import cn.shun.model.MyFile;
 import jakarta.annotation.Resource;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.web.bind.annotation.*;

 import java.io.ByteArrayInputStream;
 import java.io.InputStream;
 import java.util.List;

 /**
  * <p>Project: sboot_2023-cn.shun.controller-UploadController
  * <p>Powered by yishun On 2023-04-17 18:15:24
  *
  * @author yishun [2465734101@qq.com]
  * @version 1.0
  * @since 17
  */
 @Slf4j
 @RestController
 @RequestMapping("/api/upload")
 public class UploadController {
     @Resource
     MemberDao memberDao;
     @Resource
     MyFileDao myFileDao;

     @PostMapping
     public String upload(@RequestBody UploadInfo uploadInfo) {
         String name = uploadInfo.getName();
         String[] imgData = StrUtil.splitToArray(uploadInfo.getBase64(), "base64,");
         byte[] bytes = Base64.decode(imgData[1]);
         name = IdUtil.fastSimpleUUID() + "_" + name;
         //获取拓展名
         String ext = StrUtil.subAfter(name, ".", true);
         switch (ext) {
             case "xlsx":
                 insertExcel(bytes);
                 break;
             case "docx":
                 insertWord(bytes);
             default:
                 break;
         }
         FileUtil.writeBytes(bytes, "D:/JavaDev/nginx-1.23.3/html/images/" + name);
         String url = "http://127.0.0.1/images/" + name;
         myFileDao.insert(MyFile.builder().name(name).url(url).build());
         return url;
     }

     private void insertWord(byte[] bytes) {
         InputStream is = new ByteArrayInputStream(bytes);
         //....

     }

     private void insertExcel(byte[] bytes) {
         InputStream is = new ByteArrayInputStream(bytes);
         ExcelReader reader = ExcelUtil.getReader(is);
         List<Member> members = reader.readAll(Member.class);
         //批量插入数据库
         int rows = memberDao.insertBatch(members);
         log.info("插入行数:{}", rows);
     }

     @GetMapping
     public List<MyFile> selectList() {
         return myFileDao.selectList();
     }
 }
